package myoa.permission

import myoa.Role

class PermissionSetting {
    final String MAOHAO = ':'
    final String DOUHAO = ','
    final String XINGHAO = '*'
    final String KONG = ''

    List<ControllerNameObj> setting

    PermissionSetting(List<ControllerNameObj> setting) {
        this.setting = setting
    }

    void grant(Map params) {
        setting.each { con ->
            con.actionNameObjList.each { act ->
                String check = params."${act.fullName}"
                if (check == 'on') {
                    con.partActionAllowed = true
                    act.allowed = true
                }
            }
            con.synAct2Con()
        }
    }

    void grant(Role role) {
        role.permissions.each {     //company:list,edit
            String[] permParts = it.replaceAll(/\s/, KONG).split(MAOHAO)  //remove all empty space at first
            String controllerName = permParts[0]  //company
            List<String> actionNameList = permParts[1].split(DOUHAO).toList()      //list, edit
            ControllerNameObj con = setting.find { it.name == controllerName }
            con.partActionAllowed = true
            actionNameList.each { actionName ->
                if (actionName == XINGHAO) {        // 星号 * for allow all actions
                    con.allActionAllowed = true     // 自动同步星号
                } else {
                    ActionNameObj act = con.actionNameObjList.find { it.name == actionName }
                    act.allowed = true
                }
            }
            con.synAct2Con()   // 手动同步星号
        }
    }

    //permission string sample: company:list,edit
    List<String> toPermissions() {
        List<String> re = []
        (setting.findAll { it.partActionAllowed }).each { con ->
            String part1 = con.name + MAOHAO  //company:
            StringBuffer part2 = new StringBuffer()
            if (con.allActionAllowed) {
                part2.append(XINGHAO)     //company:*
            } else {
                con.actionNameObjList.each {
                    if (it.allowed) part2.append(DOUHAO + it.name)  //company:,list,view
                }
            }
            String permissionStr = part1 + part2.replaceFirst(DOUHAO, KONG)   //company:list,view
            println permissionStr
            re << permissionStr
        }
        return re
    }

    ActionNameObj find(ControllerNameObj c, ActionNameObj a) {
        ControllerNameObj conFind = setting.find { it.name == c.name }
        conFind.actionNameObjList.find { it.name == a.name }
    }

    String toString() {
        StringBuffer sb = new StringBuffer()
        setting.each { con ->
            sb.append(con.name + MAOHAO).append(con.actionNameObjList.size()).append("\n\r")
        }
        return sb.toString()
    }
}
